package com.xteam.xnetworkdisk.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import com.xteam.xnetworkdisk.common.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@Component
public class SessionValidationFilter extends GenericFilterBean {

    private static final String LOGIN_PATH = "/sys/user/login"; // 登录接口的路径
    private static final String SEND_EMAIL_RESET_PATH = "/sys/user/sendEmailResetP";
    private static final String RESET_PASSWORD_PATH = "/sys/user/resetPassword";
    private static final String SEND_EMAIL_CAPTCHA_PATH = "/sys/user/sendEmailCaptcha";
    private static final String VERIFICATION_PATH = "/sys/user/verification";
    private static final String SHARE_LIST_PATH = "/sys/share/list";
    private static final String SESSION_SET_PATH = "/sys/session/set";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info("注册过滤器...");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        HttpSession sessionq = httpRequest.getSession(false);
        System.out.println("OPTIONS放行的session:"+sessionq);

        if(httpRequest.getMethod().equals("OPTIONS")){
            chain.doFilter(request, response);
            return;
        }
        String requestUri = httpRequest.getRequestURI();

        // 如果是登录接口，则直接放行
        if (LOGIN_PATH.equals(requestUri) || SEND_EMAIL_RESET_PATH.equals(requestUri) || RESET_PASSWORD_PATH.equals(requestUri)
        || SEND_EMAIL_CAPTCHA_PATH.equals(requestUri) || VERIFICATION_PATH.equals(requestUri) || SHARE_LIST_PATH.equals(requestUri) ||
        SESSION_SET_PATH.equals(requestUri) ){
            chain.doFilter(request, response);
            log.info("直接放行");
            return;
        }

        // 检查 session 的有效性
        HttpSession session = httpRequest.getSession(false);
        System.out.println("未放行的session:"+session);
        if (session == null || session.getAttribute("userid") == null) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not authenticated");
            return;
        }

        log.info("当前用户id：{}", (Integer) session.getAttribute("userid"));
        CurrentUser.setCurrentUserId((Integer) session.getAttribute("userid"));
        chain.doFilter(request, response);
        CurrentUser.removeCurrentUserId();
    }
}
